package image2

import (
	"errors"
	"github.com/nfnt/resize"
	"math"
)

type Picture struct {
	Path   string
	X      int
	Y      int
	Width  int
	Height int
	Circle bool
}

func (p *Picture) Process(canvas *Canvas) error {
	var endX, endY = p.X + p.Width, p.Y + p.Height
	if endX > canvas.Width || endY > canvas.Height {
		return errors.New("数组越界！")
	}
	img, err := loadImage(p.Path)
	if err != nil {
		return err
	}
	if p.Width > 0 || p.Height > 0 {
		img = resize.Resize(uint(p.Width), uint(p.Height), img, resize.Lanczos3)
	} else {
		p.Width, p.Height = loadImageSize(img)
	}

	if p.Circle == false {
		for x := p.X; x < endX; x++ {
			for y := p.Y; y < endY; y++ {
				if canvas.Placeholder[x][y] == 1 {
					continue
				}
				canvas.Placeholder[x][y] = 1
				canvas.Canvas.Set(x, y, img.At(x-p.X, y-p.Y))
			}
		}
	} else {
		var (
			width, height, d int
		)
		width = img.Bounds().Max.X - img.Bounds().Min.X
		height = img.Bounds().Max.Y - img.Bounds().Min.Y
		d = width
		if width > height {
			d = height
		}
		for x := p.X; x < endX; x++ {
			for y := p.Y; y < endY; y++ {
				if canvas.Placeholder[x][y] == 1 {
					continue
				}
				dis := math.Sqrt(math.Pow(float64(x-p.X-d/2), 2) + math.Pow(float64(y-p.Y-d/2), 2))
				if dis < float64(d)/2 {
					canvas.Placeholder[x][y] = 1
					canvas.Canvas.Set(x, y, img.At(x-p.X, y-p.Y))
				}
			}
		}
	}
	return nil
}
